#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildVegetationManagerCreateEditJobForm():
    Dict={}
    VegetationManagerJobChoices=[]
    VegetationManagerJobChoices.append([-1, 'New'])
    VegetationManagerJobs = VegetationManagerJob.objects.all().order_by('id')
    for i in VegetationManagerJobs:
        if i.Description:
            VegetationManagerJobChoices.append([i.id, str(i.id) + ': ' + i.Description.replace('\r\n', '')])
        else:
            VegetationManagerJobChoices.append([i.id, str(i.id)])
    Dict['SelectVegetationManagerJob']=forms.ChoiceField(VegetationManagerJobChoices, required=False)
    VegetationManagerCrewChoices=[]
    VegetationManagerCrews = VegetationManagerCrew.objects.all().order_by('id')
    for i in VegetationManagerCrews:
        DisplayString=str(i.Company.Name) + ': ' + str(i.WorkerQuantity) + ' Workers; Radio #' + i.RadioNumber
        VegetationManagerCrewChoices.append([i.id, DisplayString])
    VegetationManagerJobStatusChoices=[]
    VegetationManagerJobStatuses=VegetationManagerJobStatus.objects.all().order_by('id')
    for i in VegetationManagerJobStatuses:
        VegetationManagerJobStatusChoices.append([i.id, i.Name])
    Dict['SelectVegetationManagerCrew']=forms.ChoiceField(VegetationManagerCrewChoices, required=False)
    Dict['SelectVegetationManagerJobStatus']=forms.ChoiceField(VegetationManagerJobStatusChoices, required=False)
    Dict['Description']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40}))
    Dict['WorkStartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['WorkEndDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['HoursWorkedQuantity']=forms.FloatField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['WidthInFeet']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SubstationName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['CircuitName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['TrimRightOfWayIndicator']=forms.BooleanField(required=False)
    Dict['ActiveIndicator']=forms.BooleanField(required=False)
    return Dict


def ProcessVegetationManagerCreateEditJobForm(form, UserName):
    SelectVegetationManagerJobid=COOPGIS_FormMisc.FormGetInteger(form, 'SelectVegetationManagerJob')
    SelectVegetationManagerCrewid=COOPGIS_FormMisc.FormGetInteger(form, 'SelectVegetationManagerCrew')
    SelectVegetationManagerJobStatusid=COOPGIS_FormMisc.FormGetInteger(form, 'SelectVegetationManagerJobStatus')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    WorkStartDate=COOPGIS_FormMisc.FormGetDateTime(form, 'WorkStartDate')
    WorkEndDate=COOPGIS_FormMisc.FormGetDateTime(form, 'WorkEndDate')
    HoursWorkedQuantity=COOPGIS_FormMisc.FormGetFloat(form, 'HoursWorkedQuantity')
    WidthInFeet=COOPGIS_FormMisc.FormGetInteger(form, 'WidthInFeet')
    SubstationName=COOPGIS_FormMisc.FormGetString(form, 'SubstationName')
    CircuitName=COOPGIS_FormMisc.FormGetString(form, 'CircuitName')
    TrimRightOfWayIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'TrimRightOfWayIndicator')
    ActiveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ActiveIndicator')
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=False
    if SelectVegetationManagerJobid == -1:
        NewIndicator=True
        SelectVegetationManagerJobid=''
    if UpdateIndicator:
        if NewIndicator:
            command=Command().Create(Name='CreateVegetationManagerJob',
                                     CommandUserName = UserName,
                                     CommandCreateDateTime = datetime.datetime.now(),
                                     Description=Description,
                                     VegetationManagerCrewid=SelectVegetationManagerCrewid,
                                     WorkStartDate=WorkStartDate,
                                     WorkEndDate=WorkEndDate,
                                     VegetationManagerJobStatusid=SelectVegetationManagerJobStatusid,
                                     HoursWorkedQuantity=HoursWorkedQuantity,
                                     WidthInFeet=WidthInFeet,
                                     ActiveIndicator=ActiveIndicator,
                                     SubstationName=SubstationName,
                                     CircuitName=CircuitName,
                                     TrimRightOfWayIndicator=TrimRightOfWayIndicator)
            SelectVegetationManagerJob=command.Process()
        else:
            command=Command().Create(Name='EditVegetationManagerJob',
                                     CommandUserName = UserName,
                                     CommandCreateDateTime = datetime.datetime.now(),
                                     VegetationManagerJobid=SelectVegetationManagerJobid,
                                     VegetationManagerCrewid=SelectVegetationManagerCrewid,
                                     Description=Description,
                                     WorkStartDate=WorkStartDate,
                                     WorkEndDate=WorkEndDate,
                                     VegetationManagerJobStatusid=SelectVegetationManagerJobStatusid,
                                     HoursWorkedQuantity=HoursWorkedQuantity,
                                     WidthInFeet=WidthInFeet,
                                     ActiveIndicator=ActiveIndicator,
                                     TrimRightOfWayIndicator=TrimRightOfWayIndicator,
                                     SubstationName=SubstationName,
                                     CircuitName=CircuitName)
            SelectVegetationManagerJob=command.Process()
        SelectVegetationManagerJobid = SelectVegetationManagerJob.id
    return SelectVegetationManagerJobid


def PopulateVegetationManagerCreateEditJobForm(form, SelectVegetationManagerJobid):
    form.setData({'UpdateIndicator': False})
    if SelectVegetationManagerJobid:
        SelectVegetationManagerJob = VegetationManagerJob.objects.filter(id=SelectVegetationManagerJobid)[0]
        form.data['SelectVegetationManagerJob']=SelectVegetationManagerJob.id
        form.data['SelectVegetationManagerCrew']=SelectVegetationManagerJob.VegetationManagerCrew.id
        form.data['SelectVegetationManagerJobStatus']=SelectVegetationManagerJob.VegetationManagerJobStatus.id
        form.data['Description']=SelectVegetationManagerJob.Description
        form.data['WorkStartDate']=SelectVegetationManagerJob.WorkStartDate
        form.data['WorkEndDate']=SelectVegetationManagerJob.WorkEndDate
        form.data['HoursWorkedQuantity']=SelectVegetationManagerJob.HoursWorkedQuantity
        form.data['WidthInFeet']=SelectVegetationManagerJob.WidthInFeet
        form.data['SubstationName']=SelectVegetationManagerJob.SubstationName
        form.data['CircuitName']=SelectVegetationManagerJob.CircuitName
        form.setData({'TrimRightOfWayIndicator': SelectVegetationManagerJob.TrimRightOfWayIndicator})
        form.setData({'ActiveIndicator': SelectVegetationManagerJob.ActiveIndicator})
    else:
        form.data['SelectVegetationManagerJob']=-1
        form.data['SelectVegetationManagerCrew']=-1
        form.data['SelectVegetationManagerJobStatus']=-1
        form.data['Description']=''
        form.data['WorkStartDate']=''
        form.data['WorkEndDate']=''
        form.data['HoursWorkedQuantity']=0.0
        form.data['WidthInFeet']=0
        form.data['SubstationName']=''
        form.data['CircuitName']=''
        form.setData({'TrimRightOfWayIndicator': False})
        form.setData({'ActiveIndicator': False})
    return form


def BuildVegetationManagerWorkJobForm(DefaultMap):
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all().order_by('Name')
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    VegetationManagerJobChoices=[]
    VegetationManagerJobs = VegetationManagerJob.objects.all().order_by('id')
    for i in VegetationManagerJobs:
        DisplayString = '#' + str(i.id) + ': ' + str(i.Description)
        VegetationManagerJobChoices.append([i.id, DisplayString])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['SelectVegetationManagerJob']=forms.ChoiceField(VegetationManagerJobChoices, required=False)
    Dict['SelectStationTagNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['UpdateIndicator'] = forms.BooleanField(required=False)
    Dict['DeleteSelectedSpansFromJobIndicator'] = forms.BooleanField(required=False)
    #Attribute Fields
    Dict['SelectedVegetationManagerJobSpanCount']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'3', 'READONLY':'True'}))
    Dict['SymbologyJobYear']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['CircuitNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40}))
    Dict['WKTPolygon']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':7, 'READONLY': 'True'}))
    return Dict

def ProcessVegetationManagerWorkJobForm(form, UserName):
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    DeleteSelectedSpansFromJobIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteSelectedSpansFromJobIndicator')
    SymbologyJobYear=COOPGIS_FormMisc.FormGetInteger(form, 'SymbologyJobYear')
    CircuitNumber=COOPGIS_FormMisc.FormGetInteger(form, 'CircuitNumber')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    SelectedVegetationManagerJobid = COOPGIS_FormMisc.FormGetInteger(form, 'SelectVegetationManagerJob')
    Polygon = COOPGIS_FormMisc.FormGetGeometryFromWKT(form, 'WKTPolygon')
    if UpdateIndicator and SelectedVegetationManagerJobid:
        if Polygon:
            Spans = Span.objects.filter(Line__within=Polygon)
            SpanList = list(Spans.values_list('id', flat=True))
        elif CircuitNumber:
            Assemblies = Assembly.objects.filter(CompatibleUnit__SpanIndicator=True).filter(CircuitNumber=CircuitNumber)
            SpanList = list(Assemblies.values_list('Span__id', flat=True).distinct())
            DeleteSelectedSpansFromJobIndicator=False #add only when using circuitnumber, otherwise it could get confusing
        JobStatus = VegetationManagerJobStatus.objects.filter(Name='Completed')[0]
        try:
            SelectedVegetationManagerJob = VegetationManagerJob.objects.get(id=SelectedVegetationManagerJobid)
        except DoesNotExist:
            raise Exception('No such job: ' + str(SelectedVegetationManagerJobid))

        if DeleteSelectedSpansFromJobIndicator:
            RemoveSpansFromJob(SpanList, SelectedVegetationManagerJob, UserName)
        else:
            AddSpansToJob(SpanList, SelectedVegetationManagerJob, UserName, SymbologyJobYear)

    return SelectedVegetationManagerJobid

def PopulateVegetationManagerWorkJobForm(form, SelectedVegetationManagerJobid):
    try:
        SelectedVegetationManagerJob = VegetationManagerJob.objects.filter(id=SelectedVegetationManagerJobid)[0]
    except:
        SelectedVegetationManagerJob=''
    form.setData({'UpdateIndicator': False})
    form.setData({'DeleteSelectedSpansFromJobIndicator': False})
    form.data['SymbologyJobYear']=''
    form.data['CircuitNumber']=''
    form.data['WKTPolygon']=''
    if SelectedVegetationManagerJob:
        JobSpans = VegetationManagerJobSpan.objects.filter(VegetationManagerJob=SelectedVegetationManagerJob)
        form.data['SelectVegetationManagerJob']=SelectedVegetationManagerJob.id
        form.data['SelectedVegetationManagerJobSpanCount']=JobSpans.count()
        form.data['Description']=SelectedVegetationManagerJob.Description
    else:
        form.data['SelectVegetationManagerJob']=-1
        form.data['SelectedVegetationManagerJobSpanCount']=0
        form.data['Description']=''
    return form    
        
def AddSpansToJob(SpanIDList, vegetationManagerJob, UserName, SymbologyJobYear):
    for i in SpanIDList:
        if VegetationManagerJobSpan.objects.filter(VegetationManagerJob = vegetationManagerJob).filter(Spanid=i).exists():
            continue
        span = Span.objects.filter(id=i)[0]
        command=Command().Create(Name='CreateVegetationManagerJobSpan', CommandUserName=UserName,
                              CommandCreateDateTime=datetime.datetime.now(),
                              VegetationManagerJobid=vegetationManagerJob.id,
                              Line=span.Line, Spanid = span.id, SymbologyJobYear=SymbologyJobYear)
        command.Process()

def EditJobSpans(Spanids, vegetationManagerJob, WidthInFeet, UserName, WorkCompletedDate):
    if(vegetationManagerJob.ResidesOnServerIndicator):
        VegetationManagerJobid=vegetationManagerJob.id
        VegetationManagerJobIndexWhenReverseSorted=-1
    else:
        VegetationManagerJobid=-1
        VegetationManagerJobs=VegetationManagerJob.objects.all().order_by('-id')
        i = 0
        while(True):
            if(VegetationManagerJobs[i].id==vegetationManagerJob.id):
                 VegetationManagerJobIndexWhenReverseSorted=i
                 break
            i=i + 1
    for spanid in Spanids:
        if(VegetationManagerJobSpan.objects.filter(Spanid=spanid).filter(VegetationManagerJob=vegetationManagerJob)):
            command=Command().Create(Name='EditVegetationManagerJobSpan', CommandUserName=UserName, 
                           Line=Span.objects.filter(id=spanid)[0].Line, WidthInFeet=WidthInFeet, 
                           VegetationManagerJobid=VegetationManagerJobid, VegetationManagerJobSpanid=spanid,
                           VegetationManagerJobIndexWhenReverseSorted=VegetationManagerJobIndexWhenReverseSorted,
                           WorkCompletedDate=WorkCompletedDate)
            command.Process()

def RemoveSpansFromJob(SpanIDList, vegetationManagerJob, UserName):
    for i in SpanIDList:
        JobSpan= VegetationManagerJobSpan.objects.filter(VegetationManagerJob = vegetationManagerJob).filter(Spanid=i)
        if not JobSpan.count():
            continue
        command=Command().Create(Name='DeleteVegetationManagerJobSpan', CommandUserName=UserName,
                                 CommandCreateDateTime=datetime.datetime.now(),
                                 VegetationManagerJobSpanid=JobSpan[0].id)
        command.Process()

def ProcessCircuitTrace(form, UserName):
    """Traces a Circuit Downstream from the substation and highlights it on the map"""
    try:  
        CircuitToTrace=int(form.data['TraceCircuitNumber'])
    except:
        CircuitToTrace=None
    if(CircuitToTrace):
        circuitTrace=CircuitTrace()
        circuitTrace.PerformTrace(CircuitToTrace, UserName)



def BuildVegetationManagerForm(DefaultMap):
    Dict={}
    #Create the VegetationManagerJob Choices
    VegetationManagerJobChoices=[]
    VegetationManagerJobs=VegetationManagerJob.objects.all().exclude(VegetationManagerJobStatus__Name='Complete').exclude(VegetationManagerJobStatus__Name='Cancelled')
    VegetationManagerJobChoices.append(['-1', 'None'])
    for i in VegetationManagerJobs:
        VegetationManagerJobChoices.append([i.id, str(i.id) + ' ' + str(i.Description)])
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all()
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    Dict['VegetationManagerJob']=forms.ChoiceField(VegetationManagerJobChoices, required=False)
    Dict['AddSpans']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
    Dict['RemoveSpans']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
    Dict['GeoTraceIndicator'] = forms.BooleanField(required=False)
    Dict['GeoTraceStartStationid']=forms.CharField(max_length = 250, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['GeoTraceSpanidsToStopAt']=forms.CharField(max_length = 250, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['AddTraceToJobIndicator']=forms.BooleanField(required=False)
    Dict['RemoveTraceFromJobIndicator']=forms.BooleanField(required=False)
    Dict['WidthInFeet']=forms.CharField(max_length = 250, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['EditJobSpansIndicator']=forms.BooleanField(required=False)
    Dict['WorkCompletedDate']=forms.CharField(max_length = 250, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['SelectSpanid']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'4'}))
    Dict['SelectStationid']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'3'}))
    Dict['SelectStationTagNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'3'}))
    Dict['CircuitTraceCircuitNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'3'}))
    Dict['CircuitTraceIndicator']=forms.BooleanField(required=False)
    Dict['CircuitTraceStartTag']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'3'}))
    Dict['CircuitTraceEndTag']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'3'}))
    Dict['AddCircuitTraceToJobIndicator']=forms.BooleanField(required=False)
    Dict['RemoveCircuitTraceFromJobIndicator']=forms.BooleanField(required=False)
    return Dict


def ProcessVegetationManagerForm(form, UserName):
    try:
        vegetationManagerJob=VegetationManagerJob.objects.filter(id=int(form.data['VegetationManagerJob']))[0]
    except:
        vegetationManagerJob=None
    try: 
        Temp=form.data['AddSpans'].split(',')
        AddSpans=[]
        for i in Temp:
            try:
                AddSpans.append(Span.objects.filter(id=int(i.strip()))[0].id)
            except:
                pass
    except:
        AddSpans=[]
    try: 
        Temp=form.data['RemoveSpans'].split(',')
        RemoveSpans=[]
        for i in Temp:
            try:
                RemoveSpans.append(Span.objects.filter(id=int(i.strip()))[0].id)
            except:
                pass
    except:
        RemoveSpans=[]
    
    GeoTraceIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'GeoTraceIndicator')
    try: 
        if(form.data['GeoTraceStartStationid'][0].lower() == 't'):
                form.data['GeoTraceStartStationid']=Assembly.objects.filter(TagNumber__exact=form.data['GeoTraceStartStationid'][1:])[0].Station.id
        GeoTraceStartStationid=int(form.data['GeoTraceStartStationid'])
        GeoTraceStartStation=Station.objects.filter(id__exact=GeoTraceStartStationid)[0]
    except:
        GeoTraceStartStation=''
    try: 
        GeoTraceSpanidsToStopAtString=form.data['GeoTraceSpanidsToStopAt']
        Temp=GeoTraceSpanidsToStopAtString.split(',')
        GeoTraceSpanidsToStopAt=[]
        for i in Temp:
            GeoTraceSpanidsToStopAt.append(int(i.strip()))
        GeoTraceSpansToStopAt=[]
        for i in Temp:
            try:
                GeoTraceSpansToStopAt.append(Span.objects.filter(id=i)[0])
            except:
                pass
    except:
        GeoTraceSpansToStopAt=[]
    try:
        WidthInFeet=float(form.data['WidthInFeet'])
    except:
        if(vegetationManagerJob):
            WidthInFeet=vegetationManagerJob.WidthInFeet
        else:
            WidthInFeet=None

    EditJobSpansIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'EditJobSpansIndicator')
    try:
        WorkCompletedDate=COOPGIS_String.StringDateTimeToDateTime(form.data['WorkCompletedDate'])
    except:
        WorkCompletedDate=datetime.datetime.today()

    AddTraceToJobIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'AddTraceToJobIndicator')
    RemoveTraceFromJobIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'RemoveTraceFromJobIndicator')
    CircuitTraceIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'CircuitTraceIndicator')
    CircuitTraceCircuitNumber=COOPGIS_FormMisc.FormGetInteger(form, 'CircuitTraceCircuitNumber', Default=None)
    CircuitTraceStartTag=COOPGIS_FormMisc.FormGetString(form, 'CircuitTraceStartTag')
    CircuitTraceEndTag=COOPGIS_FormMisc.FormGetString(form, 'CircuitTraceEndTag')
    AddCircuitTraceToJobIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'AddCircuitTraceToJobIndicator')
    RemoveCircuitTraceFromJobIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'RemoveCircuitTraceFromJobIndicator')

    #End Reading Form Section
    CircuitSpans=[]
    if(CircuitTraceCircuitNumber and CircuitTraceIndicator):
        trace=CircuitTrace()
        TraceMessage=trace.PerformTrace(CircuitTraceCircuitNumber, UserName, StartTagNumber=CircuitTraceStartTag, EndTagNumber=CircuitTraceEndTag)
        CircuitTraceSpansToAdd=CircuitTrace.objects.filter(UserName=UserName, AfterStartTagIndicator=True, AfterEndTagIndicator=False)
        Spans=[]
        for i in CircuitTraceSpansToAdd:
            CircuitSpans.append(i.Span.id)
    if(GeoTraceIndicator):
        trace=CircuitTrace()
        GeoTraceStations, GeoTraceSpans = trace.PerformGeoTrace(GeoTraceStartStation,  GeoTraceSpansToStopAt, UserName)
    else:
        GeoTraceStations=[]
        GeoTraceSpans=[]
    if(vegetationManagerJob and not EditJobSpansIndicator):
        if(AddTraceToJobIndicator and vegetationManagerJob):
            AddSpansToJob(GeoTraceSpans, vegetationManagerJob, WidthInFeet, UserName, WorkCompletedDate)
        elif(RemoveTraceFromJobIndicator and vegetationManagerJob):
            RemoveSpansFromJob(GeoTraceSpans, vegetationManagerJob, UserName)
        if(AddCircuitTraceToJobIndicator and vegetationManagerJob):
            AddSpansToJob(CircuitSpans, vegetationManagerJob, WidthInFeet, UserName, WorkCompletedDate)
        elif(RemoveCircuitTraceFromJobIndicator and vegetationManagerJob):
            RemoveSpansFromJob(CircuitSpans, vegetationManagerJob, UserName)
        if(AddSpans):
            AddSpansToJob(AddSpans, vegetationManagerJob, WidthInFeet, UserName, WorkCompletedDate)
        if(RemoveSpans):
            RemoveSpansFromJob(RemoveSpans, vegetationManagerJob, UserName)
    if(vegetationManagerJob and EditJobSpansIndicator):
        if(AddTraceToJobIndicator):
            EditJobSpans(GeoTraceSpans, vegetationManagerJob, WidthInFeet, UserName, WorkCompletedDate)
        if(AddSpans):
            EditJobSpans(AddSpans, vegetationManagerJob, WidthInFeet, UserName, WorkCompletedDate)
    return vegetationManagerJob
        
def PopulateVegetationManagerForm(form, vegetationManagerJob):
    if(vegetationManagerJob):
        form.data['VegetationManagerJob']=vegetationManagerJob.id
    else:
        form.data['VegetationManagerJob']=-1 
    form.data['AddSpans']=''
    form.data['RemoveSpans']=''
    form.data['AddTraceToJobIndicator']=False
    form.data['RemoveTraceFromJobIndicator']=False
    form.data['EditJobSpansIndicator']=False
    form.data['AddCircuitTraceToJobIndicator']=False
    form.data['RemoveCircuitTraceFromJobIndicator']=False
    return form






def BuildVegetationManagerDetailsForm(SpecialBuildFormInfo):
    if(SpecialBuildFormInfo):
        ShowAllVegetationManagerJobIndicator=SpecialBuildFormInfo['ShowAllVegetationManagerJobIndicator']
        ShowAllVegetationManagerCrewIndicator=SpecialBuildFormInfo['ShowAllVegetationManagerCrewIndicator']
        ShowAllCompanyIndicator=SpecialBuildFormInfo['ShowAllCompanyIndicator']
    else:
        ShowAllVegetationManagerJobIndicator=False
        ShowAllVegetationManagerCrewIndicator=False
        ShowAllCompanyIndicator=False
    Dict={}
    #Create the VegetationManagerJob Choices
    VegetationManagerJobChoices=[]
    if(ShowAllVegetationManagerJobIndicator):
        VegetationManagerJobs=VegetationManagerJob.objects.all().order_by('WorkStartDate')
    else:
        VegetationManagerJobs=VegetationManagerJob.objects.all().exclude(VegetationManagerJobStatus__Name='Complete').exclude(VegetationManagerJobStatus__Name='Canceled').order_by('WorkStartDate')
    VegetationManagerJobChoices.append(['-1', 'None'])
    VegetationManagerJobChoices.append(['-2', 'New'])
    for i in VegetationManagerJobs:
        VegetationManagerJobChoices.append([i.id, str(i.id) + ' ' + str(i.WorkStartDate) + ' ' + str(i.SubstationName) + ' ' + str(i.CircuitName) + ' ' + str(i.Description)])

    if(ShowAllVegetationManagerJobIndicator):
        VegetationManagerJobs=VegetationManagerJob.objects.all()
    else:
        VegetationManagerJobs=VegetationManagerJob.objects.all().exclude(VegetationManagerJobStatus__Name='Complete').exclude(VegetationManagerJobStatus__Name='Canceled')
    #Create the VegetationManagerCrew Choices
    VegetationManagerCrewChoices=[]
    if(ShowAllVegetationManagerCrewIndicator):
        VegetationManagerCrews=VegetationManagerCrew.objects.all()
    else:
        VegetationManagerCrews=VegetationManagerCrew.objects.filter(ActiveIndicator=True)
    VegetationManagerCrewChoices.append(['-1', 'None'])
    VegetationManagerCrewChoices.append(['-2', 'New'])
    for i in VegetationManagerCrews:
        VegetationManagerCrewChoices.append([i.id, str(i.id) + ' *' + str(i.RadioNumber) + '*  ' + str(i.WorkStartDate)])
    VegetationManagerCrewChoicesNoNew=[]
    VegetationManagerCrewChoicesNoNew.append(['-1', 'None'])
    for i in VegetationManagerCrews:
        VegetationManagerCrewChoicesNoNew.append([i.id, str(i.id) + ' *' + str(i.RadioNumber) + '*  ' + str(i.WorkStartDate)])
    #Create the VegetationManagerJobStatus Choices
    VegetationManagerJobStatusChoices=[]
    VegetationManagerJobStatuses=VegetationManagerJobStatus.objects.all()
    VegetationManagerJobStatusChoices.append(['-1', 'None'])
    VegetationManagerJobStatusChoices.append(['-2', 'New'])
    for i in VegetationManagerJobStatuses:
        VegetationManagerJobStatusChoices.append([i.id, str(i.Name)])
    #Create the VegetationManagerJobStatusChoicesNoNew
    VegetationManagerJobStatusChoicesNoNew=[]
    VegetationManagerJobStatusChoicesNoNew.append(['-1', 'None'])
    for i in VegetationManagerJobStatuses:
        VegetationManagerJobStatusChoicesNoNew.append([i.id, str(i.Name)])

    #Create the VegetationManagerCompany Choices
    VegetationManagerCompanyChoices=[]
    if(ShowAllCompanyIndicator):
        VegetationManagerCompanies=Company.objects.all()
    else:
        VegetationManagerCompanies=Company.objects.filter(VegetationManagementIndicator=True)
    VegetationManagerCompanyChoices.append(['-1', 'None'])
    VegetationManagerCompanyChoices.append(['-2', 'New'])
    for i in VegetationManagerCompanies:
        VegetationManagerCompanyChoices.append([i.id, str(i.Name)])
    VegetationManagerCompanyChoicesNoNew=[]
    for i in VegetationManagerCompanies:
        VegetationManagerCompanyChoicesNoNew.append([i.id, str(i.Name)])
    #Create the StakerWorkOrder Choices
    StakerWorkOrderChoices=[]
    StakerWorkOrders=StakerWorkOrder.objects.all().exclude(DeletedIndicator=True).order_by('WorkOrderNumber', 'Name')
    StakerWorkOrderChoices.append(['-1', 'None'])
    for i in StakerWorkOrders:
        StakerWorkOrderChoices.append([i.id, str(i.WorkOrderNumber) + '  ' + str(i.Name)])
    #End Choice Creation Section

    Dict['ShowAllVegetationManagerJobIndicator']=forms.BooleanField(required=False)
    Dict['ShowAllVegetationManagerCrewIndicator']=forms.BooleanField(required=False)
    Dict['ShowAllCompanyIndicator']=forms.BooleanField(required=False)

    Dict['VegetationManagerJobSelection']=forms.ChoiceField(VegetationManagerJobChoices, required=False)
    Dict['VegetationManagerJobid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['VegetationManagerJobUpdateIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerJobDeleteIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerJobDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerCrewid']=forms.ChoiceField(VegetationManagerCrewChoicesNoNew, required=False)
    Dict['VegetationManagerJobWorkStartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerJobWorkEndDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerJobJobStatusid']=forms.ChoiceField(VegetationManagerJobStatusChoicesNoNew, required=False)
    Dict['VegetationManagerJobHoursWorkedQuantity']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerJobWidthInFeet']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerJobActiveIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerJobStakerWorkOrder']=forms.ChoiceField(StakerWorkOrderChoices, required=False)
    Dict['VegetationManagerJobTrimRightOfWayIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerJobSubstationName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerJobCircuitName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    
    Dict['VegetationManagerCrewSelection']=forms.ChoiceField(VegetationManagerCrewChoices, required=False)
    Dict['VegetationManagerCrewid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['VegetationManagerCrewUpdateIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerCrewDeleteIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerCrewWorkerQuantity']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerCrewCompanyid']=forms.ChoiceField(VegetationManagerCompanyChoicesNoNew, required=False)
    Dict['VegetationManagerCrewWorkStartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerCrewWorkEndDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerCrewActiveIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerCrewRadioNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
   
    Dict['VegetationManagerJobStatusSelection']=forms.ChoiceField(VegetationManagerJobStatusChoices, required=False)    
    Dict['VegetationManagerJobStatusid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['VegetationManagerJobStatusUpdateIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerJobStatusDeleteIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagerJobStatusName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['VegetationManagerJobStatusDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    return Dict


def ProcessVegetationManagerDetailsFormJob(form, UserName):
    try:
        VegetationManagerJobSelectionid=int(form.data['VegetationManagerJobSelection'])
        if(VegetationManagerJobSelectionid == -2):
            vegetationManagerJobSelection=None
        else:
            vegetationManagerJobSelection=VegetationManagerJob.objects.filter(id=VegetationManagerJobSelectionid)[0]
    except:
        VegetationManagerJobSelectionid=-1
        vegetationManagerJobSelection=None
    try:
        VegetationManagerJobid=int(form.data['VegetationManagerJobid'])
        vegetationManagerJob=VegetationManagerJob.objects.filter(id=VegetationManagerJobid)[0]
    except:
        VegetationManagerJobid=None
        vegetationManagerJob=None
    try:
        VegetationManagerJobUpdateIndicator=bool(form.data['VegetationManagerJobUpdateIndicator'] == 'on')
    except:
        VegetationManagerJobUpdateIndicator=False
    try:
        VegetationManagerJobDeleteIndicator=bool(form.data['VegetationManagerJobDeleteIndicator'] == 'on')
    except:
        VegetationManagerJobDeleteIndicator=False
    try:
        VegetationManagerJobDescription=form.data['VegetationManagerJobDescription']
    except:
        VegetationManagerJobDescription=''
    try:
        VegetationManagerJobCrewid=int(form.data['VegetationManagerJobCrewid'])
        vegetationManagerJobCrew=VegetationManagerCrew.objects.filter(id=VegetationManagerJobCrewid)[0]
        VegetationManagerJobCrewIndexWhenReverseSorted=vegetationManagerJobCrew.GetIndexWhenReverseSorted()
        if(not vegetationManagerJobCrew.ResidesOnServerIndicator):
            vegetationManagerJobCrewid = -1
    except:
        VegetationManagerJobCrewid=None
        vegetationManagerJobCrew=None
        VegetationManagerJobCrewIndexWhenReverseSorted=-1
    try:
        VegetationManagerJobWorkStartDate=COOPGIS_String.StringDateTimeToDateTime(form.data['VegetationManagerJobWorkStartDate'])
    except:
        VegetationManagerJobWorkStartDate=None
    try:
        VegetationManagerJobWorkEndDate=COOPGIS_String.StringDateTimeToDateTime(form.data['VegetationManagerJobWorkEndDate'])
    except:
        VegetationManagerJobWorkEndDate=None
    try:
        VegetationManagerJobJobStatusid=int(form.data['VegetationManagerJobJobStatusid'])
        vegetationManagerJobJobStatus=VegetationManagerJobStatus.objects.filter(id=VegetationManagerJobJobStatusid)[0]
        VegetationManagerJobJobStatusIndexWhenReverseSorted=vegetationManagerJobJobStatus.GetIndexWhenReverseSorted()
        if(not vegetationManagerJobJobStatus.ResidesOnServerIndicator):
            vegetationManagerJobJobStatusid=-1
    except:
        VegetationManagerJobJobStatusid=None
        vegetationManagerJobJobStatus=None
        VegetationManagerJobJobStatusIndexWhenReverseSorted=-1
    try:
        VegetationManagerJobHoursWorkedQuantity=float(form.data['VegetationManagerJobHoursWorkedQuantity'])
    except:
        VegetationManagerJobHoursWorkedQuantity=None
    try:
        VegetationManagerJobWidthInFeet=float(form.data['VegetationManagerJobWidthInFeet'])
    except:
        VegetationManagerJobWidthInFeet=None
    try:
        VegetationManagerJobActiveIndicator=bool(form.data['VegetationManagerJobActiveIndicator'] == 'on')
    except:
        VegetationManagerJobActiveIndicator=False
    try:
        VegetationManagerJobTrimRightOfWayIndicator=bool(form.data['VegetationManagerJobTrimRightOfWayIndicator'] == 'on')
    except:
        VegetationManagerJobTrimRightOfWayIndicator=False
    try:
        VegetationManagerJobSubstationName=form.data['VegetationManagerJobSubstationName']
    except:
        VegetationManagerJobSubstationName=''
    try:
        VegetationManagerJobCircuitName=form.data['VegetationManagerJobCircuitName']
    except:
        VegetationManagerJobCircuitName=''
    try:
        StakerWorkOrderid=int(form.data['VegetationManagerJobStakerWorkOrder'])
        stakerWorkOrder=StakerWorkOrder.objects.filter(id=StakerWorkOrderid)[0]
        StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=stakerWorkOrder.GetCommandidData()
    except:
        StakerWorkOrderid=stakerWorkOrder=None
        StakerWorkOrderIndexWhenReverseSorted=-1
    if(VegetationManagerJobUpdateIndicator):
        if(VegetationManagerJobSelectionid==-2): #Create a New One
            command=Command()
            command=command.Create(Name='CreateVegetationManagerJob', Description=VegetationManagerJobDescription, 
                                   VegetationManagerCrewid=VegetationManagerJobCrewid, 
                                   VegetationManagerCrewIndexWhenReverseSorted=VegetationManagerJobCrewIndexWhenReverseSorted,
                                   WorkStartDate=VegetationManagerJobWorkStartDate, WorkEndDate=VegetationManagerJobWorkEndDate,
                                   VegetationManagerJobStatusid=VegetationManagerJobJobStatusid, 
                                   VegetationManagerJobStatusIndexWhenReverseSorted=VegetationManagerJobJobStatusIndexWhenReverseSorted,
                                   HoursWorkedQuantity=VegetationManagerJobHoursWorkedQuantity, WidthInFeet=VegetationManagerJobWidthInFeet,
                                   ActiveIndicator=VegetationManagerJobActiveIndicator, StakerWorkOrderid=StakerWorkOrderid,
                                   StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted, CommandUserName=UserName,
                                   TrimRightOfWayIndicator=VegetationManagerJobTrimRightOfWayIndicator,
                                   SubstationName=VegetationManagerJobSubstationName, CircuitName=VegetationManagerJobCircuitName)
            vegetationManagerJob=command.Process()
        elif(VegetationManagerJobid): #Edit an Existing One
            if(vegetationManagerJob.ResidesOnServerIndicator):
                command=Command()
                command=command.Create(Name='EditVegetationManagerJob', VegetationManagerJobid=VegetationManagerJobid, 
                                       Description=VegetationManagerJobDescription, 
                                       VegetationManagerCrewid=VegetationManagerJobCrewid, 
                                       VegetationManagerCrewIndexWhenReverseSorted=VegetationManagerJobCrewIndexWhenReverseSorted,
                                       WorkStartDate=VegetationManagerJobWorkStartDate, WorkEndDate=VegetationManagerJobWorkEndDate,
                                       VegetationManagerJobStatusid=VegetationManagerJobJobStatusid, 
                                       VegetationManagerJobStatusIndexWhenReverseSorted=VegetationManagerJobJobStatusIndexWhenReverseSorted,
                                       HoursWorkedQuantity=VegetationManagerJobHoursWorkedQuantity, WidthInFeet=VegetationManagerJobWidthInFeet,
                                       ActiveIndicator=VegetationManagerJobActiveIndicator, StakerWorkOrderid=StakerWorkOrderid, 
                                       StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted, CommandUserName=UserName,
                                       TrimRightOfWayIndicator=VegetationManagerJobTrimRightOfWayIndicator,
                                       SubstationName=VegetationManagerJobSubstationName, CircuitName=VegetationManagerJobCircuitName)
                command.Process()
            else:
                command=vegetationManagerJob.CreateCommand
                command.Description=VegetationManagerJobDescription
                command.VegetationManagerCrewid=VegetationManagerJobCrewid
                command.VegetationManagerCrewIndexWhenReverseSorted=VegetationManagerJobCrewIndexWhenReverseSorted
                command.WorkStartDate=VegetationManagerJobWorkStartDate
                command.WorkEndDate=VegetationManagerJobWorkEndDate
                command.VegetationManagerJobStatusid=VegetationManagerJobJobStatusid
                command.VegetationManagerJobStatusIndexWhenReverseSorted=VegetationManagerJobJobStatusIndexWhenReverseSorted
                command.HoursWorkedQuantity=VegetationManagerJobHoursWorkedQuantity
                command.WidthInFeet=VegetationManagerJobWidthInFeet
                command.ActiveIndicator=VegetationManagerJobActiveIndicator
                command.StakerWorkOrderid=StakerWorkOrderid
                command.StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted
                command.TrimRightOfWayIndicator=VegetationManagerJobTrimRightOfWayIndicator
                command.SubstationName=VegetationManagerJobSubstationName
                command.CircuitName=VegetationManagerJobCircuitName
                command.save()
                vegetationManagerJob.Description=VegetationManagerJobDescription
                vegetationManagerJob.VegetationManagerCrew=vegetationManagerJobCrew
                vegetationManagerJob.WorkStartDate=VegetationManagerJobWorkStartDate
                vegetationManagerJob.WorkEndDate=VegetationManagerJobWorkEndDate
                vegetationManagerJob.VegetationManagerJobStatus=vegetationManagerJobJobStatus
                vegetationManagerJob.HoursWorkedQuantity=VegetationManagerJobHoursWorkedQuantity
                vegetationManagerJob.WidthInFeet=VegetationManagerJobWidthInFeet
                vegetationManagerJob.ActiveIndicator=VegetationManagerJobActiveIndicator
                vegetationManagerJob.StakerWorkOrder=stakerWorkOrder
                vegetationManagerJob.TrimRightOfWayIndicator=VegetationManagerJobTrimRightOfWayIndicator
                vegetationManagerJob.SubstationName=VegetationManagerJobSubstationName
                vegetationManagerJob.CircuitName=VegetationManagerJobCircuitName
                vegetationManagerJob.save()
    elif(VegetationManagerJobDeleteIndicator):
        DeleteVegetationManagerJob(VegetationManagerJobid, UserName)
        return None
    if(vegetationManagerJob and VegetationManagerJobUpdateIndicator):
        return vegetationManagerJob
    else:
        return vegetationManagerJobSelection

def DeleteVegetationManagerJob(VegetationManagerJobid, UserName):
    ObjectToDelete=VegetationManagerJob.objects.filter(id=VegetationManagerJobid)[0]
    if(ObjectToDelete.ResidesOnServerIndicator):   #Create the appropriate Command if on the server
        command=Command()
        command=command.Create(Name='DeleteVegetationManagerJob', VegetationManagerJobid=VegetationManagerJobid, CommandUserName=UserName)
        command=command.Process()
        return "Deleted a VegetationManagerJob object by creating a delete command"
    else:  #Delete the appropriate commands that would create it on the server if it only exists on the client
        ObjectToDelete.CreateCommand.delete()
        ObjectToDelete.delete()
        return "Deleted a VegetationManagerJob object by deleting a create command"

def ProcessVegetationManagerDetailsFormCrew(form, UserName):
    try:
        VegetationManagerCrewSelectionid=int(form.data['VegetationManagerCrewSelection'])
        if(VegetationManagerCrewSelectionid == -2):
            vegetationManagerCrewSelection=None
        else:
            vegetationManagerCrewSelection=VegetationManagerCrew.objects.filter(id=VegetationManagerCrewSelectionid)[0]
    except:
        VegetationManagerCrewSelectionid=-1
        vegetationManagerCrewSelection=None
    try:
        VegetationManagerCrewid=int(form.data['VegetationManagerCrewid'])
        vegetationManagerCrew=VegetationManagerCrew.objects.filter(id=VegetationManagerCrewid)[0]
    except:
        VegetationManagerCrewid=None
        vegetationManagerCrew=None
    try:
        VegetationManagerCrewUpdateIndicator=bool(form.data['VegetationManagerCrewUpdateIndicator'] == 'on')
    except:
        VegetationManagerCrewUpdateIndicator=False
    try:
        VegetationManagerCrewDeleteIndicator=bool(form.data['VegetationManagerCrewDeleteIndicator'] == 'on')
    except:
        VegetationManagerCrewDeleteIndicator=False
    try:
        VegetationManagerCrewWorkerQuantity=int(form.data['VegetationManagerCrewWorkerQuantity'])
    except:
        VegetationManagerCrewWorkerQuantity=None
    try:
        VegetationManagerCrewCompanyid=int(form.data['VegetationManagerCrewCompanyid'])
        vegetationManagerCrewCompany=Company.objects.filter(id=VegetationManagerCrewCompanyid)[0]
        VegetationManagerCrewCompanyIndexWhenReverseSorted=vegetationManagerCrewCompany.GetIndexWhenReverseSorted()
    except:
        VegetationManagerCrewCompanyid=None
        vegetationManagerCrewCompany=None
        VegetationManagerCrewCompanyIndexWhenReverseSorted=-1
    try:
        VegetationManagerCrewWorkStartDate=COOPGIS_String.StringDateTimeToDateTime(form.data['VegetationManagerCrewWorkStartDate'])
    except:
        VegetationManagerCrewWorkStartDate=None
    try:
        VegetationManagerCrewWorkEndDate=COOPGIS_String.StringDateTimeToDateTime(form.data['VegetationManagerCrewWorkEndDate'])
    except:
        VegetationManagerCrewWorkEndDate=None
    try:
        VegetationManagerCrewActiveIndicator=bool(form.data['VegetationManagerCrewActiveIndicator']=='on')
    except:
        VegetationManagerCrewActiveIndicator=False
    try:
        VegetationManagerCrewRadioNumber=form.data['VegetationManagerCrewRadioNumber']
    except:
        VegetationManagerCrewRadioNumber=''
    if(VegetationManagerCrewUpdateIndicator):
        if(VegetationManagerCrewSelectionid==-2): #Create a New One
            command=Command()
            command=command.Create(Name='CreateVegetationManagerCrew', CommandUserName=UserName, 
                                   WorkerQuantity=VegetationManagerCrewWorkerQuantity, 
                                   Companyid=VegetationManagerCrewCompanyid, 
                                   CompanyIndexWhenReverseSorted=VegetationManagerCrewCompanyIndexWhenReverseSorted, 
                                   WorkStartDate=VegetationManagerCrewWorkStartDate, WorkEndDate=VegetationManagerCrewWorkEndDate,
                                   ActiveIndicator=VegetationManagerCrewActiveIndicator, RadioNumber=VegetationManagerCrewRadioNumber)
            vegetationManagerCrew=command.Process()
        elif(VegetationManagerCrewid): #Edit an Existing One
            if(vegetationManagerCrew.ResidesOnServerIndicator):
                command=Command()
                command=command.Create(Name='EditVegetationManagerCrew', VegetationManagerCrewid=VegetationManagerCrewid,
                                   WorkerQuantity=VegetationManagerCrewWorkerQuantity, 
                                   Companyid=VegetationManagerCrewCompanyid, 
                                   CompanyIndexWhenReverseSorted=VegetationManagerCrewCompanyIndexWhenReverseSorted, 
                                   WorkStartDate=VegetationManagerCrewWorkStartDate, WorkEndDate=VegetationManagerCrewWorkEndDate,
                                   ActiveIndicator=VegetationManagerCrewActiveIndicator, RadioNumber=VegetationManagerCrewRadioNumber)
                command.Process()
            else:
                command=vegetationManagerCrew.CreateCommand
                command.WorkerQuantity=VegetationManagerCrewWorkerQuantity
                command.Companyid=VegetationManagerCrewCompanyid
                command.CompanyIndexWhenReverseSorted=VegetationManagerCrewCompanyIndexWhenReverseSorted
                command.WorkStartDate=VegetationManagerCrewWorkStartDate
                command.WorkEndDate=VegetationManagerCrewWorkEndDate
                command.ActiveIndicator=VegetationManagerCrewActiveIndicator
                command.RadioNumber=VegetationManagerCrewRadioNumber
                command.save()
                vegetationManagerCrew.WorkerQuantity=VegetationManagerCrewWorkerQuantity
                vegetationManagerCrew.Company=vegetationManagerCrewCompany
                vegetationManagerCrew.WorkStartDate=VegetationManagerCrewWorkStartDate
                vegetationManagerCrew.WorkEndDate=VegetationManagerCrewWorkEndDate
                vegetationManagerCrew.ActiveIndicator=VegetationManagerCrewActiveIndicator
                vegetationManagerCrew.RadioNumber=VegetationManagerCrewRadioNumber
                vegetationManagerCrew.save()
    elif(VegetationManagerCrewDeleteIndicator):
        DeleteVegetationManagerCrew(VegetationManagerCrewid, UserName)
        return None
    if(vegetationManagerCrew and VegetationManagerCrewUpdateIndicator):
        return vegetationManagerCrew
    else:
        return vegetationManagerCrewSelection

def DeleteVegetationManagerCrew(VegetationManagerCrewid, UserName):
    ObjectToDelete=VegetationManagerCrew.objects.filter(id=VegetationManagerCrewid)[0]
    if(ObjectToDelete.ResidesOnServerIndicator):   #Create the appropriate Command if on the server
        command=Command()
        command=command.Create(Name='DeleteVegetationManagerCrew', VegetationManagerCrewid=VegetationManagerCrewid, CommandUserName=UserName)
        command=command.Process()
        return "Deleted a VegetationManagerCrew object by creating a delete command"
    else:  #Delete the appropriate commands that would create it on the server if it only exists on the client
        ObjectToDelete.CreateCommand.delete()
        ObjectToDelete.delete()
        return "Deleted a VegetationManagerCrew object by deleting a create command"




def ProcessVegetationManagerDetailsFormJobStatus(form, UserName):
    try:
        VegetationManagerJobStatusSelectionid=int(form.data['VegetationManagerJobStatusSelection'])
        if(VegetationManagerJobStatusSelectionid == -2):
            vegetationManagerJobStatusSelection=None
        else:
            vegetationManagerJobStatusSelection=VegetationManagerJobStatus.objects.filter(id=VegetationManagerJobStatusSelectionid)[0]
    except:
        VegetationManagerJobStatusSelectionid=-1
        vegetationManagerJobStatusSelection=None

    try:
        VegetationManagerJobStatusid=int(form.data['VegetationManagerJobStatusid'])
        vegetationManagerJobStatus=VegetationManagerJobStatus.objects.filter(id=VegetationManagerJobStatusid)[0]
    except:
        VegetationManagerJobStatusid=None
        vegetationManagerJobStatus=None
    try:
        VegetationManagerJobStatusUpdateIndicator=bool(form.data['VegetationManagerJobStatusUpdateIndicator']=='on')
    except:
        VegetationManagerJobStatusUpdateIndicator=False
    try:
        VegetationManagerJobStatusDeleteIndicator=bool(form.data['VegetationManagerJobStatusDeleteIndicator']=='on')
    except:
        VegetationManagerJobStatusDeleteIndicator=False
    try:
        VegetationManagerJobStatusName=form.data['VegetationManagerJobStatusName']
    except:
        VegetationManagerJobStatusName=''
    try:
        VegetationManagerJobStatusDescription=form.data['VegetationManagerJobStatusDescription']
    except:
        VegetationManagerJobStatusDescription=''
    if(VegetationManagerJobStatusUpdateIndicator):
        if(VegetationManagerJobStatusSelectionid==-2): #Create a New One
            command=Command()
            command=command.Create(Name='CreateVegetationManagerJobStatus', CommandUserName=UserName, 
                                   VegetationManagerJobStatusName=VegetationManagerJobStatusName, Description=VegetationManagerJobStatusDescription)
            vegetationManagerJobStatus=command.Process()
        elif(VegetationManagerJobStatusid): #Edit an Existing One
            if(vegetationManagerJobStatus.ResidesOnServerIndicator):
                command=Command()
                command=command.Create(Name='EditVegetationManagerJobStatus', CommandUserName=UserName, 
                                       VegetationManagerJobStatusid=VegetationManagerJobStatusid, 
                                       VegetationManagerJobStatusName=VegetationManagerJobStatusName, Description=VegetationManagerJobStatusDescription)
                command.Process()
            else:
                command=vegetationManagerJobStatus.CreateCommand
                command.VegetationManagerJobStatusName=VegetationManagerJobStatusName
                command.Description=VegetationManagerJobStatusDescription
                command.save()
                vegetationManagerJobStatus.Name=VegetationManagerJobStatusName
                vegetationManagerJobStatus.Description=VegetationManagerJobStatusDescription
                vegetationManagerJobStatus.save()
    elif(VegetationManagerJobStatusDeleteIndicator):
        DeleteVegetationManagerJobStatus(VegetationManagerJobStatusid, UserName)
        return None
    if(vegetationManagerJobStatus and VegetationManagerJobStatusUpdateIndicator):
        return vegetationManagerJobStatus
    else:
        return vegetationManagerJobStatusSelection

def DeleteVegetationManagerJobStatus(VegetationManagerJobStatusid, UserName):
    ObjectToDelete=VegetationManagerJobStatus.objects.filter(id=VegetationManagerJobStatusid)[0]
    if(ObjectToDelete.ResidesOnServerIndicator):   #Create the appropriate Command if on the server
        command=Command()
        command=command.Create(Name='DeleteVegetationManagerJobStatus', VegetationManagerJobStatusid=VegetationManagerJobStatusid, CommandUserName=UserName)
        command=command.Process()
        return "Deleted a VegetationManagerJobStatus object by creating a delete command"
    else:  #Delete the appropriate commands that would create it on the server if it only exists on the client
        ObjectToDelete.CreateCommand.delete()
        ObjectToDelete.delete()
        return "Deleted a VegetationManagerJobStatus object by deleting a create command"





def SpecialProcessVegetationManagerDetailsForm(form):
    Results={}
    Results['ShowAllVegetationManagerJobIndicator']=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowAllVegetationManagerJobIndicator')
    Results['ShowAllVegetationManagerCrewIndicator']=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowAllVegetationManagerCrewIndicator')
    Results['ShowAllCompanyIndicator']=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowAllCompanyIndicator')
    return Results





def PopulateVegetationManagerDetailsFormJob(form, vegetationManagerJob):
    try:
        form.data['VegetationManagerJobSelection']=vegetationManagerJob.id
        form.data['VegetationManagerJobid']=vegetationManagerJob.id
        form.data['VegetationManagerJobUpdateIndicator']=False
        form.data['VegetationManagerJobDeleteIndicator']=False
        form.data['VegetationManagerJobDescription']=vegetationManagerJob.Description
        try:
            form.data['VegetationManagerJobCrewid']=vegetationManagerJob.VegetationManagerCrew.id
        except:
            form.data['VegetationManagerJobCrewid']=-1
        form.data['VegetationManagerJobWorkStartDate']=vegetationManagerJob.WorkStartDate
        form.data['VegetationManagerJobWorkEndDate']=vegetationManagerJob.WorkEndDate
        try:
            form.data['VegetationManagerJobJobStatusid']=vegetationManagerJob.VegetationManagerJobStatus.id
        except:
            form.data['VegetationManagerJobJobStatusid']=-1
        form.data['VegetationManagerJobHoursWorkedQuantity']=vegetationManagerJob.HoursWorkedQuantity
        form.data['VegetationManagerJobWidthInFeet']=vegetationManagerJob.WidthInFeet
        form.data['VegetationManagerJobActiveIndicator']=vegetationManagerJob.ActiveIndicator
        if(vegetationManagerJob.StakerWorkOrder):
            form.data['VegetationManagerJobStakerWorkOrder']=vegetationManagerJob.StakerWorkOrder.id
        else:
            form.data['VegetationManagerJobStakerWorkOrder']=-1
        form.data['VegetationManagerJobTrimRightOfWayIndicator']=vegetationManagerJob.TrimRightOfWayIndicator
        form.data['VegetationManagerJobSubstationName']=vegetationManagerJob.SubstationName
        form.data['VegetationManagerJobCircuitName']=vegetationManagerJob.CircuitName
    except:
        form.data['VegetationManagerJobSelection']=-1
        form.data['VegetationManagerJobid']=''
        form.data['VegetationManagerJobUpdateIndicator']=False
        form.data['VegetationManagerJobDeleteIndicator']=False
        form.data['VegetationManagerJobDescription']=''
        form.data['VegetationManagerJobCrewid']=-1
        form.data['VegetationManagerJobWorkStartDate']=''
        form.data['VegetationManagerJobWorkEndDate']=''
        form.data['VegetationManagerJobJobStatusid']=-1
        form.data['VegetationManagerJobHoursWorkedQuantity']=''
        form.data['VegetationManagerJobWidthInFeet']=''
        form.data['VegetationManagerJobActiveIndicator']=False
        form.data['VegetationManagerJobStakerWorkOrder']=-1
        form.data['VegetationManagerJobTrimRightOfWayIndicator']=False
        form.data['VegetationManagerJobSubstationName']=''
        form.data['VegetationManagerJobCircuitName']=''
    return form


def PopulateVegetationManagerDetailsFormCrew(form, vegetationManagerCrew):
    try:
        form.data['VegetationManagerCrewSelection']=vegetationManagerCrew.id
        form.data['VegetationManagerCrewid']=vegetationManagerCrew.id
        form.data['VegetationManagerCrewUpdateIndicator']=False
        form.data['VegetationManagerCrewDeleteIndicator']=False
        form.data['VegetationManagerCrewWorkerQuantity']=vegetationManagerCrew.WorkerQuantity
        try:
            form.data['VegetationManagerCrewCompanyid']=vegetationManagerCrew.Company.id
        except:
            form.data['VegetationManagerCrewCompanyid']=-1
        form.data['VegetationManagerCrewWorkStartDate']=vegetationManagerCrew.WorkStartDate
        form.data['VegetationManagerCrewWorkEndDate']=vegetationManagerCrew.WorkEndDate
        form.data['VegetationManagerCrewActiveIndicator']=vegetationManagerCrew.ActiveIndicator
        form.data['VegetationManagerCrewRadioNumber']=vegetationManagerCrew.RadioNumber
    except:
        form.data['VegetationManagerCrewSelection']=-1
        form.data['VegetationManagerCrewid']=''
        form.data['VegetationManagerCrewUpdateIndicator']=False
        form.data['VegetationManagerCrewDeleteIndicator']=False
        form.data['VegetationManagerCrewWorkerQuantity']=''
        form.data['VegetationManagerCrewCompanyid']=-1
        form.data['VegetationManagerCrewWorkStartDate']=''
        form.data['VegetationManagerCrewWorkEndDate']=''
        form.data['VegetationManagerCrewActiveIndicator']=False
        form.data['VegetationManagerCrewRadioNumber']=''
    return form

def PopulateVegetationManagerDetailsFormJobStatus(form, vegetationManagerJobStatus):
    try:
        form.data['VegetationManagerJobStatusSelection']=vegetationManagerJobStatus.id    
        form.data['VegetationManagerJobStatusid']=vegetationManagerJobStatus.id
        form.data['VegetationManagerJobStatusUpdateIndicator']=False
        form.data['VegetationManagerJobStatusDeleteIndicator']=False
        form.data['VegetationManagerJobStatusName']=vegetationManagerJobStatus.Name
        form.data['VegetationManagerJobStatusDescription']=vegetationManagerJobStatus.Description
    except:
        form.data['VegetationManagerJobStatusSelection']=-1    
        form.data['VegetationManagerJobStatusid']=''
        form.data['VegetationManagerJobStatusUpdateIndicator']=False
        form.data['VegetationManagerJobStatusDeleteIndicator']=False
        form.data['VegetationManagerJobStatusName']=''
        form.data['VegetationManagerJobStatusDescription']=''
    return form
    


